package com.zhiqi.thread;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * @author czq
 */
public class ThreadDemoTest {

    @Test
    public void fixedDemo() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 100; i++) {
            int finalItem = i;
            executorService.execute(() -> {
                try {
                    this.biz(finalItem);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    @Test
    public void cachedDemo() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 100; i++) {
            int finalItem = i;
            executorService.execute(() -> {
                try {
                    this.biz(finalItem);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    @Test
    public void singleDemo() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 100; i++) {
            int finalItem = i;
            executorService.execute(() -> {
                try {
                    this.biz(finalItem);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    @Test
    public void exceptionDemo() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
        executorService.execute(() -> {
            System.out.println("123");
            int i = 1 / 0;
            countDownLatch.countDown();
        });
        countDownLatch.await();
    }


    public void biz(int item) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "--" + item);
        Thread.sleep(1000);
    }
}